package org.kent.w.base.common.executor;

import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
import java.util.concurrent.FutureTask;

/**
 * 线程池执行代理
 *
 * @author wu.jigang@geely.com
 * @version 1.0
 * @Date :Created by 2020/3/6.
 */
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class ExecutorServiceProxy {

    private boolean isClosed = false;

    private ExecutorService executorService;

    public ExecutorServiceProxy(ExecutorService executorService) {
        this.executorService = executorService;
    }

    /***
     * 任务并发处理
     * @param task
     * @return 异步处理返回
     */
    public <T> Future<T> submit(TraceableCallable<T> task) {

        if (isClosed) {
            throw new RuntimeException("服务中止！");
        }
        return executorService.submit(task);
    }

    /***
     * 任务并发处理
     * @param task
     * @return 异步处理返回
     */
    public void submit(TraceableRunnable task) {

        if (isClosed) {
            throw new RuntimeException("服务中止！");
        }

        executorService.submit(task);
    }

    /***
     * 任务并发处理
     * @param task
     * @return 异步处理返回
     */
    public void submit(FutureTask task) {

        if (isClosed) {
            throw new RuntimeException("服务中止！");
        }

        executorService.submit(task);
    }

    /**
     * 线程池关闭
     */
    public void close() {
        isClosed = true;

        ExecutorUtil.gracefulShutdown(this.executorService, 2000);
    }
}
